<?php
class Util
{
/******** Geter and Setter function to global values begin *****************/
public static function setGlobalValue($key,$value)
{
	$query = sprintf("REPLACE INTO `%s` SET `key`='%s',`value`='%s'",constant('DB_TABLE_KEY_VALUE'),mysql_real_escape_string($key),mysql_real_escape_string($value));
	$result=mysql_query($query);
	if($result == false)
		throw new Exception(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));

}
public static function deleteGlobalValue($key)
{
	$query = sprintf("DELETE FROM `%s` WHERE `key`='%s'",constant('DB_TABLE_KEY_VALUE'),mysql_real_escape_string($key));
	$result=mysql_query($query);
	if($result == false)
		throw new Exception(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
}
public static function getGlobalValue($key)
{
	$value = '';
	$query = sprintf("SELECT `value` FROM `%s` WHERE `key`='%s'",constant('DB_TABLE_KEY_VALUE'),mysql_real_escape_string($key));
	$result=mysql_query($query);
	if($result == false)
		throw new Exception(sprintf("%s%s%s",mysql_error(),__FILE__,__LINE__));
	if(($row = mysql_fetch_assoc($result)))
	{
		$value = $row['value'];
	}
	return $value;
}
/******** Geter and Setter function to global values end *****************/

public static function makeRandomStr($length,$onlyNumber = FALSE) 
{ 
	$possible = "123456789";
	if(!$onlyNumber)
		$possible .= "abcdefghijklmnopqrstuvwxyz"; 
	$str = ""; 
	$possibleLen = strlen($possible);
	while(strlen($str) < $length) 
	{ 
		$cIndex = mt_rand(0,$possibleLen - 1);
		
		$str .= substr($possible, $cIndex, 1); 
	} 
	return $str; 
}

public static function truncateStr($str,$length)
{
	$string = substr($str,0,$length);
	return $string;
}

public static function getFileExt($fileName)
{

// 1. The "explode/end" approach
//$ext = end(explode('.', $filename));
 
// 2. The "strrchr" approach
$ext = substr(strrchr($fileName, '.'), 1);
 
// 3. The "strrpos" approach
//$ext = substr($filename, strrpos($filename, '.') + 1);
 
// 4. The "preg_replace" approach
//$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
 
// 5. The "never use this" approach
//   From: http://php.about.com/od/finishedphp1/qt/file_ext_PHP.htm
//$exts = split("[/\\.]", $filename);
//$n = count($exts)-1;
//$ext = $exts[$n];

return $ext;
}
 public static function FSubstr($Str,$start,$strlen=10,$other=true) 
 {
    global $s;
    $Length = $strlen;
    $i = 0;
    $l = 0;
    $ll = strlen($Str);
    $s = $Str;
    $f = true;
    while ($i <= $ll) {
        if (ord($Str{$i}) < 0x80) {
              $l++;
              $i++;
        }
        else if (ord($Str{$i}) < 0xe0) {
             $l++;
             $i += 2;
        }
        else if (ord($Str{$i}) < 0xf0) {
             $l += 2;
             $i += 3;
        }
        else if (ord($Str{$i}) < 0xf8) {
             $l += 1;
             $i += 4;
        }
        else if (ord($Str{$i}) < 0xfc) {
             $l += 1;
             $i += 5;
        }
        else if (ord($Str{$i}) < 0xfe) {
             $l += 1;
             $i += 6;
        }
        if (($l >= $Length - 1) && $f)  {
             $s = substr($Str, 0, $i);
             $f = false;
        }
        if (($l > $Length) && ($i < $ll)) {
             $s = $s . '.';
             break;
        }
    }
    return $s;
 }
 /**
 /*flag: 1 addslashes 2 stripslashes 3 strip_tags 
 */
  public static function work_str($str, $flag=1)
 {
   if ($flag == 1)
   {
     if (get_magic_quotes_gpc())
	   return $str;
	 $value = addslashes($str);
   } 
   else if ($flag == 2)
   {
	 $value = stripslashes($str);
   }
   else if ($flag == 3)
   {
     if (! get_magic_quotes_gpc())
	   $str = addslashes($str);
     $value = strip_tags($str);
   } //End if
   return $value;
 }
 public static function  html_safe($str,$encode = 'UTF-8')
 {
 	return htmlentities($str,ENT_COMPAT,$encode);
 }
 public static function sql_safe($string)
 {
 	if(!$GLOBALS['magic_quotes_gpc'] || $force) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
		    $string[$key] = daddslashes($val, $force);
	}
	} else {
	$string = addslashes($string);
    }
  }
  return $string;
 }
 
 public static function get_days($length)
 {
 	$today = date('Y-m-d');
 	$list = array();
 	$list['Today'] = $today;
 	for($i=1;$i<$length;$i++)
 	{
 		$tmpDate = strtotime($today." $i day");
 	    $label = date('D',$tmpDate);
 	    $list[ $label] = date('Y-m-d',$tmpDate);
 	}
 	return $list;
 }
 
 public static function isEmail($email) {
	return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}

public static function getRemoteIP()
{
	$user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
$user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"]; 
return $user_IP;
}

public static function getSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
	  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

public static function getMonthLastDate($year,$month)
{
	return date('t',mktime(0,0,0,$month,1,$year));
}

public static function htmlStrBeforSaveDb($reqStr)
{
	if (get_magic_quotes_gpc())
		$reqStr = stripslashes($reqStr);
	$reqStr = base64_encode($reqStr);
	return $reqStr;
}
public static function htmlStrAfterReadfromDb($reqStr)
{
	return base64_decode($reqStr);
}
public static function deleteDir($dir)
{
	if(is_dir($dir))
	{
		$dp = opendir($dir);
		if(!$dp)
			throw new Exception('permission no allowed to open dir '.$dir);
		 while (($file=readdir($dp)) != false) {
		 	if($file == '.' || $file == '..')
				continue;
	 		Util::deleteDir($dir.'/'.$file);
		 }
		 closedir($dp);
		 rmdir($dir);
	}else if(is_file($dir)){
		$deleteResult = unlink($dir);
   		if($deleteResult !== true)
   			throw new Exception('delete file '.$dir.' failure');
	}else{
		throw new exception('path '.$dir.' either a dir or file');
	}
}
}
?>